package com.zhengxiang.onlinexamination.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.zhengxiang.onlinexamination.dao.*;
import com.zhengxiang.onlinexamination.entity.*;
import com.zhengxiang.onlinexamination.entity.vo.ExamResultVo;
import com.zhengxiang.onlinexamination.entity.vo.PreviewPaperVo;
import com.zhengxiang.onlinexamination.service.ExamResultService;
import com.zhengxiang.onlinexamination.service.SettingService;
import com.zhengxiang.onlinexamination.service.WaitPaperService;
import com.zhengxiang.onlinexamination.utils.SecurityUtils;
import com.zhengxiang.onlinexamination.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.jnlp.IntegrationService;
import javax.jws.Oneway;
import java.text.DateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 考试结果(ExamResult)表服务实现类
 *
 * @author makejava
 * @since 2023-04-11 20:29:19
 */
@Transactional(rollbackFor = Exception.class)
@Service("examResultService")
public class ExamResultServiceImpl extends ServiceImpl<ExamResultMapper, ExamResult> implements ExamResultService {
    @Resource
    private ExamResultMapper examResultMapper;

    @Resource
    private PreviewPaperMapper previewPaperMapper;

    @Resource
    private ExamPaperMapper examPaperMapper;

    @Autowired
    private SettingService settingService;

    @Resource
    private WaitPaperMapper waitPaperMapper;

    @Resource
    private QuMapper quMapper;

    @Override
    public ExamResultVo getExamResultInfo(ExamResultVo examResultVo) {
        QueryWrapper<ExamResult> q = new QueryWrapper<>();
        q.eq("a.wait_paper_id", examResultVo.getWaitPaperId());
        q.eq("a.user_id",SecurityUtils.getCustomerLoginUser().getCustomerUserId());
        ExamResult examResultInfo = examResultMapper.getExamResultInfo(q);
        BeanUtil.copyProperties(examResultInfo, examResultVo);
        return examResultVo;
    }
    @Override
    public ExamResultVo getExamResultInfoById(ExamResultVo examResultVo) {
        QueryWrapper<ExamResult> q = new QueryWrapper<>();
        q.eq("a.exam_result_id", examResultVo.getExamResultId());
        ExamResult examResultInfo = examResultMapper.getExamResultInfo(q);
        BeanUtil.copyProperties(examResultInfo, examResultVo);
        return examResultVo;
    }
    @Override
    public void handPaper(ExamResultVo examResultVo) {
        WaitPaper waitPaper = waitPaperMapper.selectById(examResultVo.getWaitPaperId());
        ExamPaper examPaper = examPaperMapper.selectById(waitPaper.getExamPaperId());
        List<Integer> errorQuesitonIds = new ArrayList<>();
        List<Integer> correctQuestionIds = new ArrayList<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        int examScore = 0;
        //        获取当前考试信息
        QueryWrapper<PreviewPaper> q = new QueryWrapper<>();
        q.lambda().eq(PreviewPaper::getUserId, SecurityUtils.getCustomerLoginUser().getCustomerUserId()).eq(PreviewPaper::getWaitPaperId, examResultVo.getWaitPaperId());
        List<PreviewPaper> previewPapers = previewPaperMapper.queryPaperInfo(q);
        for (PreviewPaper s : previewPapers) {
            //计算所有错题和正确题数
            if (s.getThisScore() == 0) {
                errorQuesitonIds.add(s.getQuId());
            } else {
                correctQuestionIds.add(s.getQuId());
            }
            //处理总分
            disposeScore(examScore, s);
            //处理题目数据
            disposeQuestion(mapList, s);
        }

        //正确题数
        examResultVo.setCorrectQuestion(correctQuestionIds.size());
        examResultVo.setCorrectQuesitonId(correctQuestionIds.stream().map(Object::toString).collect(Collectors.joining(",")));
        //错误题数
        examResultVo.setErrorQuestion(errorQuesitonIds.size());
        examResultVo.setErrorQuestionId(errorQuesitonIds.stream().map(Object::toString).collect(Collectors.joining(",")));
        //  得分
        examResultVo.setResultScore(examScore);
        examResultVo.setIsPass(examScore > examPaper.getPassMark() ? 1 : -1);
        examResultVo.setResultTime(30);
        //  试卷内容
        examResultVo.setPaperContent(JSONObject.toJSONString(mapList));
        examResultVo.setUserId(SecurityUtils.getCustomerLoginUser().getCustomerUserId());
        examResultVo.setUserName(SecurityUtils.getCustomerLoginUser().getUserName());
        //  记录试卷关联id
        examResultVo.setExamPaperName(waitPaper.getPaperName());
        examResultVo.setExamPaperId(waitPaper.getExamPaperId());
        examResultMapper.insert(examResultVo);
        //  清除预考数据
        UpdateWrapper<PreviewPaper> u = new UpdateWrapper<>();
        u.lambda().eq(PreviewPaper::getUserId, SecurityUtils.getCustomerLoginUser().getCustomerUserId()).eq(PreviewPaper::getWaitPaperId, examResultVo.getWaitPaperId());
        previewPaperMapper.delete(u);
        //  更新待考人数
        waitPaper.setWaitUserNum(waitPaper.getWaitUserNum() - 1);
        waitPaper.setAlreadyUserNum(waitPaper.getWaitUserNum() + 1);
        waitPaper.setWaitState(waitPaper.getWaitUserNum() == 0 ? -1 : 0);
        waitPaperMapper.updateById(waitPaper);
    }

    @Override
    public IPage queryExamResultList(ExamResultVo examResultVo) {
        QueryWrapper<ExamResult> q = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(examResultVo.getExamPaperName())) {
            q.lambda().like(ExamResult::getExamPaperName, examResultVo.getExamPaperName());
        }
        if (StringUtils.isNotEmpty(examResultVo.getUserName())) {
            q.lambda().like(ExamResult::getUserName, examResultVo.getUserName());
        }
        if (Objects.nonNull(examResultVo.getStartDate())) {
            q.ge("DATE_FORMAT(create_time,'%y-%m-%d')", DateUtil.format(examResultVo.getStartDate(), "yyyy-MM-dd"));
            q.le("DATE_FORMAT(create_time,'%y-%m-%d')", DateUtil.format(examResultVo.getEndDate(), "yyyy-MM-dd"));
        }
        return examResultMapper.selectPage(new Page<>(examResultVo.getCurrent(), examResultVo.getSize()), q);
    }

    public void disposeScore(int examScore, PreviewPaper p) {
        // 计算总得分
        examScore += p.getThisScore();
    }

    public void disposeQuestion(List<Map<String, Object>> mapList, PreviewPaper p) {
        Map<String, Object> map = new HashMap<>();
        //            题目id
        map.put("questionId", p.getQu().getQuId());
        //            题目名
        map.put("questionName", p.getQu().getContent());
        //            题库
        map.put("quBankName", p.getQu().getQuBank().getQuBankName());
        //            题目类型
        map.put("quesitonType", settingService.querySetting(2, p.getQu().getQuType()));
        //            本题得分
        map.put("thisScore", p.getThisScore());
        //            本题对错
        map.put("isCorrect", p.getIsCorrect());
        //        本题选择选项
        map.put("chooseOption", p.getChooseOption());
        map.put("chooseOptionA", setChooseOptionA(p.getChooseOption()));
        //        本题正确选项
        map.put("quChooseAnswer", p.getAnswerCorrectOption());
        //题目信息
        map.put("question", p.getQu());
        mapList.add(map);
    }

    private Object setChooseOptionA(String chooseOption) {
        StringBuffer sb = new StringBuffer();
        if(StringUtils.isNotEmpty(chooseOption)){
            String[] split = chooseOption.split(",");
            for (int i = 0; i <split.length ; i++) {
                Qu qu = quMapper.selectById(split[i]);
                sb.append(qu).append(",");
            }
            sb.substring(0,sb.toString().length()-1);
            return sb.toString();
        }else{
            return "";
        }

    }

    public static void main(String[] args) {
        String a = "https://abzy-test.oss-cn-beijing.aliyuncs.com/standard/picture/report/d8bae6ce305f4f438712cfdaead4cbe5.png," +
                "https://abzy-test.oss-cn-beijing.aliyuncs.com/standard/picture/report/0277cc45518a4691b7c67064d560eeb7.png," +
                "https://abzy-test.oss-cn-beijing.aliyuncs.com/standard/picture/report/da24f705e588424aa983ae9fb0294fa9.png";
        String[] split = a.split(",");
        System.out.println(split[0]);
    }


    @Override
    public void correctExaminationPaper(ExamResultVo examResultVo) {
        WaitPaper waitPaper = waitPaperMapper.selectById(examResultVo.getWaitPaperId());
        ExamPaper examPaper = examPaperMapper.selectById(waitPaper.getExamPaperId());
        //考试结果
        List<Map<String, Object>> mapList = new ArrayList<>();
        //总分
        int toralScore = 0;
        //答对题数
        List<Integer> successQu = new ArrayList<>();
        //错题数
        List<Integer> errorQu = new ArrayList<>();
        //已答题目列表
        List<Integer> anQuIds = new ArrayList<>();

        for (PreviewPaperVo p : examResultVo.getPreviewPaperList()) {
            QueryWrapper<PreviewPaper> paperQueryWrapper = new QueryWrapper<>();
            paperQueryWrapper.lambda().eq(PreviewPaper::getUserId, SecurityUtils.getCustomerLoginUser().getCustomerUserId())
                    .eq(PreviewPaper::getWaitPaperId, waitPaper.getWaitPaperId())
                    .eq(PreviewPaper::getQuId, p.getQuId());
            PreviewPaper previewPaper = previewPaperMapper.queryQuInfo(paperQueryWrapper);
            previewPaper.setChooseOption(p.getChooseOption());
            //单选题，判断题，多选题
            if (previewPaper.getQuType() != 4) {
                //比较选项
                if (p.getChooseOption().equals(previewPaper.getAnswerCorrect())) {
                    successQu.add(previewPaper.getQuId());
                    toralScore += previewPaper.getQuScore();
                } else {
                    errorQu.add(previewPaper.getQuId());
                }

            } else {
                //todo
                //简答题要配合els关键词进行比对打分，有点麻烦，暂时先给意思分
                successQu.add(previewPaper.getQuId());
                toralScore += previewPaper.getQuScore();
            }
            //已答题目
            anQuIds.add(p.getQuId());
            //处理题目数据
            disposeQuestion(mapList, previewPaper);
        }
        //获取所有未答的题目并统计
        QueryWrapper<PreviewPaper> paperQueryWrapper = new QueryWrapper<>();
        paperQueryWrapper.lambda().eq(PreviewPaper::getUserId, SecurityUtils.getCustomerLoginUser().getCustomerUserId())
                .eq(PreviewPaper::getWaitPaperId, waitPaper.getWaitPaperId());
        if(CollectionUtil.isNotEmpty(anQuIds)){
            paperQueryWrapper.lambda().notIn(PreviewPaper::getQuId, anQuIds);
        }

        List<PreviewPaper> previewPapers = previewPaperMapper.queryPaperInfo(paperQueryWrapper);
        if (CollectionUtil.isNotEmpty(previewPapers)) {
            for (PreviewPaper p : previewPapers) {
                errorQu.add(p.getQuId());
                //处理题目数据
                disposeQuestion(mapList, p);
            }
        }


        //正确题数
        examResultVo.setCorrectQuestion(successQu.size());
        examResultVo.setCorrectQuesitonId(successQu.stream().map(Object::toString).collect(Collectors.joining(",")));
        //错误题数
        examResultVo.setErrorQuestion(errorQu.size());
        examResultVo.setErrorQuestionId(errorQu.stream().map(Object::toString).collect(Collectors.joining(",")));
        //得分
        examResultVo.setResultScore(toralScore);
        examResultVo.setIsPass(toralScore > examPaper.getPassMark() ? 1 : -1);
        examResultVo.setResultTime(30);
        //试卷内容
        examResultVo.setPaperContent(JSONObject.toJSONString(mapList));
        examResultVo.setUserId(SecurityUtils.getCustomerLoginUser().getCustomerUserId());
        examResultVo.setUserName(SecurityUtils.getCustomerLoginUser().getUserName());
        //记录试卷关联id
        examResultVo.setExamPaperName(waitPaper.getPaperName());
        examResultVo.setExamPaperId(waitPaper.getExamPaperId());
        examResultMapper.insert(examResultVo);
        //  清除预考数据
        UpdateWrapper<PreviewPaper> u = new UpdateWrapper<>();
        u.lambda().eq(PreviewPaper::getUserId, SecurityUtils.getCustomerLoginUser().getCustomerUserId()).eq(PreviewPaper::getWaitPaperId, examResultVo.getWaitPaperId());
        previewPaperMapper.delete(u);
        //  更新待考人数
        waitPaper.setWaitUserNum(waitPaper.getWaitUserNum() - 1);
        waitPaper.setAlreadyUserNum(waitPaper.getWaitUserNum() + 1);
        waitPaper.setWaitState(waitPaper.getWaitUserNum() == 0 ? -1 : 0);
        waitPaperMapper.updateById(waitPaper);

    }


}
